package models

import (
	"gorm.io/gorm"
	"mishop/entitys"
)

type OrderLog struct {
	gorm.Model
	OrderID     int                `json:"order_id"`
	OrderStatus entitys.OrderStatus `json:"order_status"`
	Remark      string             `json:"remark"`
	db          *gorm.DB           `json:"-"`
}

func (OrderLog) TableName() string {
	return "orders"
}

func (p *OrderLog) Create(c *OrderLog) (*OrderLog, error) {
	result := p.db.Create(c)
	if result.Error != nil {
		return nil, result.Error
	}
	return c, nil
}

func (p *OrderLog) Update(c *OrderLog) (*OrderLog, error) {
	result := p.db.Updates(c)
	if result.Error != nil {
		return nil, result.Error
	}
	return c, nil
}

func (p *OrderLog) Delete(addressId int) error {
	result := p.db.Delete(&OrderLog{}, addressId)
	return result.Error
}

func (p *OrderLog) FindByID(address_id uint) (model *OrderLog, err error) {
	model = &OrderLog{}
	model.ID = address_id
	result := p.db.First(model)
	err = result.Error
	return
}

func (p OrderLog) FindByUserID(page, rows int, user_id uint) (pages *Pages, error error) {
	var data []OrderLog
	var all int64
	pages = &Pages{}
	query := p.db.Model(OrderLog{}).Where("user_id = ?", user_id)
	//all
	result := query.Count(&all)
	if result.Error != nil {
		return nil, result.Error
	}
	query.Limit(rows).Offset((page - 1) * rows).Find(&data)
	result = query.Count(&all)
	if result.Error != nil {
		return nil, result.Error
	}
	return NewPages(page, rows, all, data), nil
}

type IOrderLog interface {
	FindByID(addressId uint) (*OrderLog, error)
	FindByUserID(page, rows int, userId uint) (pages *Pages, error error)
	Create(c *OrderLog) (*OrderLog, error)
	Update(c *OrderLog) (*OrderLog, error)
	Delete(addressId int) error
}

func NewOrderLog(db *gorm.DB) IOrderLog {
	return &OrderLog{db: db}
}
